package pwd.allen.web.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncExecutionAspectSupport;
import org.springframework.aop.interceptor.AsyncExecutionInterceptor;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步配置方法一
 * @author 门那粒沙
 * @create 2021-01-23 20:15
 **/
//@EnableAsync//开启@Async注解异步处理
//@Configuration
public class AsyncConfig {

    private static final Logger logger = LoggerFactory.getLogger(AsyncConfig.class);

    /**
     * 将Executor包装成TtlExecutor使之支持线程池的线程变量共享，如果不包装的话，可能获取的共享变量是之前的
     * 名字一定要指定taskExecutor，除非创建的Executor是TaskExecutor类型
     *
     * 默认Executor为SimpleAsyncTaskExecutor()
     * @see AsyncExecutionInterceptor#getDefaultExecutor(org.springframework.beans.factory.BeanFactory)
     *
     * @return
     */
    @Bean("taskExecutor")
    public Executor myExecutor() {
        // 包装成TtlExecutors，以实现线程池层级的线程变量共享
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setKeepAliveSeconds(30);
        executor.setQueueCapacity(5);
        executor.setThreadNamePrefix("myExecutor-");
        executor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor exe) -> {
            logger.warn("当前任务线程池队列已满.");
        });
        executor.initialize();  // 如果用TtlExecutors包装，则需要手动调用初始化方法，否则报错：java.lang.IllegalStateException: ThreadPoolTaskExecutor not initialized
        return TtlExecutors.getTtlExecutor(executor);
    }
}
